/*
 * @Date: 2022-03-26 13:13:08
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-11-19 13:26:35
 * @FilePath: \vue-admin-ts\src\components\menu\menu.tsx
 * @Description: something
 */
import { defineComponent, PropType, useAttrs, DefineComponent } from "vue";
import { MenuItem } from "./type";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
export default defineComponent({
  props: {
    data: {
      type: Array as PropType<MenuItem[]>,
      required: true,
    },
    defaultActive: {
      type: String,
      default: "",
    },
    router: {
      type: Boolean,
      default: false,
    },
    children: {
      type: String,
      default: "children",
    },
    // 菜单标识的键名
    index: {
      type: String,
      default: "index",
    },
  },
  emits: ["clickItem"],
  setup(props, ctx) {
    const emits = ctx.emit;
    let attrs = useAttrs();
    const clickItemHandle = (item: any) => {
      emits("clickItem", item);
    };
    const renderIcon = (icon?: string) => {
      if (!icon) {
        return null;
      }
      icon = icon.slice(0, 1).toUpperCase() + icon.slice(1).toLowerCase();
      if (icon === "Chat") {
        icon = "ChatRound";
      }
      const IconComp = (
        ElementPlusIconsVue as { [key: string]: DefineComponent }
      )[icon];

      return (
        <el-icon>
          <IconComp />
        </el-icon>
      );
    };
    const renderMenu = (data: any[]) => {
      return data.map((item: any) => {
        //处理图标
        let slots = {
          title: () => {
            return (
              <>
                {renderIcon(item.icon) ? renderIcon(item.icon) : null}
                <span>{item.name}</span>
              </>
            );
          },
        };
        //递归子菜单
        if (item.children && item.children.length) {
          return (
            <el-sub-menu index={item.index} v-slots={slots}>
              {renderMenu(item.children)}
            </el-sub-menu>
          );
        }
        //无子菜单
        return (
          <el-menu-item
            index={item.index}
            onClick={() => {
              clickItemHandle(item);
            }}
          >
            {item.icon ? <item.i /> : ""}

            <span>{item.name}</span>
          </el-menu-item>
        );
      });
    };
    return () => {
      return (
        <el-menu
          class="menu-icon-svg"
          default-active={props.defaultActive}
          router={props.router}
          {...attrs}
        >
          {renderMenu(props.data)}
        </el-menu>
      );
    };
  },
});
